package htmlParser

import (
	"io"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

// NewDocumentFromReader 获取 DOM 文档
func NewDocumentFromReader(r io.Reader) (*goquery.Document, error) {
	return goquery.NewDocumentFromReader(r)
}

// WalkElement 遍历指定 DOM 元素
func WalkElement(doc *goquery.Selection, selector string, walkFunc func(element *goquery.Selection) bool) {
	doc.Find(selector).EachWithBreak(func(i int, selection *goquery.Selection) bool {
		return walkFunc(selection)
	})
}

// WalkALinks 遍历 A 连接
func WalkALinks(doc *goquery.Selection, filter string, walkFunc func(element *goquery.Selection) bool) {
	doc.Find("a").Filter(filter).EachWithBreak(func(i int, selection *goquery.Selection) bool {
		return walkFunc(selection)
	})
}

// WalkImages 遍历 img 标签
func WalkImages(doc *goquery.Selection, filter string, walkFunc func(element *goquery.Selection) bool) {
	doc.Find("img").Filter(filter).EachWithBreak(func(i int, selection *goquery.Selection) bool {
		return walkFunc(selection)
	})
}

// GetElement 返回一个指定 DOM 元素
func GetElement(doc *goquery.Selection, selectors ...string) *goquery.Selection {
	clone := doc.Clone()
	for _, s := range selectors {
		clone = clone.Find(s)
	}

	return clone.First()
}

// GetText 返回指定 DOM 元素包括的文本
func GetText(doc *goquery.Selection, selectors ...string) string {
	return strings.TrimSpace(GetElement(doc, selectors...).Text())
}

// GetHTML 返回指定 DOM 元素包括的HTML文本
func GetHTML(doc *goquery.Selection, selectors ...string) (ret string, e error) {
	return GetElement(doc, selectors...).Html()
}
